<template>
  <div>
    <CategorySelector :isDisabled="!isShowAttrList"></CategorySelector>
    <el-card>
      <div v-if="isShowAttrList">
        <el-button
          type="primary"
          :disabled="!categoryStore.category3Id"
          :icon="Plus"
          @click="toAddAttrInfo"
          >添加属性</el-button
        >
        <el-table border :data="attrList" style="margin-top: 10px">
          <el-table-column
            label="序号"
            type="index"
            width="80"
            align="center"
          ></el-table-column>
          <el-table-column
            label="属性名称"
            prop="attrName"
            width="160"
          ></el-table-column>
          <el-table-column label="属性值列表">
            <template v-slot="{ row }">
              <el-tag
                v-for="attrValue in row.attrValueList"
                :key="attrValue.id"
                style="margin-right: 6px"
                >{{ attrValue.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160">
            <template v-slot="{ row }">
              <el-tooltip
                class="box-item"
                effect="dark"
                content="编辑"
                placement="top"
              >
                <el-button
                  type="warning"
                  size="small"
                  :icon="Edit"
                  @click="toEditAttrInfo(row)"
                ></el-button>
              </el-tooltip>

              <el-popconfirm
                width="220"
                confirm-button-text="确定"
                cancel-button-text="取消"
                :icon="InfoFilled"
                icon-color="#626AEF"
                title="您真的要删除此条属性吗?"
                @confirm="confirmEvent(row.id)"
                @cancel="cancelEvent"
              >
                <template #reference>
                  <el-button
                    title="删除"
                    type="danger"
                    size="small"
                    :icon="Delete"
                  ></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-else>
        <el-form :model="attrInfo" class="demo-form-inline">
          <el-form-item label="属性名">
            <el-input
              v-model="attrInfo.attrName"
              placeholder="请输入属性名"
              style="margin-left: 10px; width: 200px"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              :disabled="!attrInfo.attrName"
              :icon="Plus"
              @click="toAddAttrValue"
              >添加属性值</el-button
            >
            <el-button @click="isShowAttrList = true"> 取消</el-button>
          </el-form-item>
        </el-form>
        <el-table border :data="attrInfo.attrValueList" style="margin: 10px 0">
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="80"
          ></el-table-column>
          <el-table-column label="属性值名称">
            <template v-slot="{ row, $index }">
              <el-input
                :ref="(input:any)=>inputRef[$index]=input"
                size="small"
                v-model="row.valueName"
                v-show="row.isShowInput"
                placeholder="请输入属性值"
                @blur="toDeleteCurrentRow(row, $index)"
              ></el-input>
              <span
                v-show="!row.isShowInput"
                style="display: inline-block; width: 100%"
                @dblclick="toEditValueName(row, $index)"
                >{{ row.valueName }}</span
              >
            </template>
          </el-table-column>

          <el-table-column label="操作" width="280">
            <template v-slot="{ row, $index }">
              <el-popconfirm
                width="220"
                confirm-button-text="确定"
                cancel-button-text="取消"
                :icon="InfoFilled"
                icon-color="#626AEF"
                title="您真的要删除此条属性值吗?"
                @confirm="toRemoveAttrValue($index)"
              >
                <template #reference>
                  <el-button
                    title="删除"
                    type="danger"
                    size="small"
                    :icon="Delete"
                  ></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          :disabled="!attrInfo.attrValueList.length"
          @click="toSaveAttrInfo"
          >保存
        </el-button>
        <el-button @click="isShowAttrList = true">取消</el-button>
      </div>
    </el-card>
  </div>
</template>
<script lang="ts">
import CategorySelector from '@/components/CategorySelector/index.vue';
export default {
  name: 'Attr',
  components: {
    CategorySelector,
  },
};
</script>

<script lang="ts" setup>
import { ref, watch, reactive, nextTick } from 'vue';
import { Plus, Edit, Delete, InfoFilled } from '@element-plus/icons-vue';
import { useCategoryListStore } from '@/stores/categoryList';
import {
  reqDeleteAttrInfo,
  reqGetAttrListData,
  reqSaveOrUpdateAttrInfo,
} from '@/api/product/attr';
import { ElMessage, type InputInstance } from 'element-plus';
import type {
  AttrInfoModel,
  AttrListModel,
  AttrValueInfoModel,
} from '@/api/product/model/attrModel';

const categoryStore = useCategoryListStore();
const isShowAttrList = ref(true);
const inputRef = ref<InputInstance[]>([]);
// 属性列表
const attrList = ref<AttrListModel>([]);

// 定义一个属性对象 里面包含属性名和对应的属性值
const attrInfo = reactive<AttrInfoModel>({
  attrName: '',
  attrValueList: [],
  // attrValueList: [{valueName:'',其它属性}, {}]
  categoryId: -1, // 对应的三级分类id
  categoryLevel: 3, // 等级 默认就是3
});

// 1. 定义一个根据一二三级导航来获取属性列表的函数
const getAttrListData = async () => {
  // 获取三级分类下对应的列表数据
  const { category1Id, category2Id, category3Id } = categoryStore;
  const result = await reqGetAttrListData({
    category1Id,
    category2Id,
    category3Id,
  });
  attrList.value = result;
};

// 2. 监听三级导航分类的变化 根据当前三级id来获取属性列表
watch(
  () => categoryStore.category3Id,
  async (category3Id) => {
    if (!category3Id) {
      // 清空数组
      attrList.value = [];
      return;
    }

    // 获取属性列表数据
    getAttrListData();
  },
  { immediate: true }
);

// 3. 单击确定的时候 删除属性
const confirmEvent = async (attrId: number) => {
  await reqDeleteAttrInfo(attrId);
  // 提示用户删除成功
  ElMessage.success('删除属性成功了...');
  // 获取属性列表数据
  getAttrListData();
};

// 4. 取消删除属性
const cancelEvent = () => {
  console.log('000!');
};

// 5. 添加 属性值
const toAddAttrValue = () => {
  // 1. 给attrInfo.attrValueList数组追加数据
  attrInfo.attrValueList.push({ valueName: '', isShowInput: true });

  // 2. 给即将要添加的属性值那一行的输入框一个自动焦点效果
  nextTick(() => {
    // inputRef.value?.focus();
    //另一种写法
    inputRef.value[attrInfo.attrValueList.length - 1].focus();
  });
};

// 6. 属性值输入框 失去焦点时的效果
const toDeleteCurrentRow = (row: AttrValueInfoModel, index: number) => {
// 1. 失去焦点以后没有内容便删除此行
  if (!row.valueName.trim()) return attrInfo.attrValueList.splice(index, 1);

  // 2 输入了数据后失去了焦点 应该做一个切换
  row.isShowInput = false;
};

// 7. 去更改属性值
const toEditValueName = (row: AttrValueInfoModel, index: number) => {
  // 1. 实现一个切换效果 显示出来输入框
  row.isShowInput = true;

  // 2. 自动让当前项获得焦点
  nextTick(() => {
    console.log('111', inputRef.value);
    // inputRef.value?.focus();
    inputRef.value[index].focus();
  });
};

// 8. 去删除属性值
const toRemoveAttrValue = (index: number) => {
  console.log(index);
  attrInfo.attrValueList.splice(index, 1);
  ElMessage.success('属性值删除成功...');
};

// 9. 添加或更新平台属性
const toSaveAttrInfo = async () => {
  attrInfo.categoryId = categoryStore.category3Id as number;
  // 1. 添加或更新数据
  await reqSaveOrUpdateAttrInfo(attrInfo);

  // 2. 提示用户操作成功
  ElMessage({
    type: 'success',
    message: '操作平台属性成功了...',
  });

  // 3. 跳转到属性列表组件 也就是实现一个切换
  isShowAttrList.value = true;

  //4. 刷新属性列表页面
  if (!attrInfo.id) {
    getAttrListData();
  }
};

// 10. 去添加属性时清空旧值
const toAddAttrInfo = () => {
  //  实现切换
  isShowAttrList.value = false;

  //  清空旧值
  Object.assign(attrInfo, { attrName: '', attrValueList: [] });

  // 3 清除id
  delete attrInfo.id;
};

// 11. 编辑平台属性之数据回显
const toEditAttrInfo = (row: AttrInfoModel) => {
  isShowAttrList.value = false;
  // 给attrInfo赋值
  Object.assign(attrInfo, row);
};
</script>
<style></style>
